//
//  ExpandLabel.swift
//  XiaohuijiVPN
//
//  Created by whale on 2022/10/21.
//

import UIKit
import YYText
class ExpandLabel: ICBaseView {

    var font: UIFont = .font(13) {
        didSet {
            lbl.font = font
        }
    }
    
    var textColor: UIColor = .subTitle {
        didSet {
            lbl.textColor = textColor
        }
    }
    
    var text: String? {
        didSet {
            initFrame()
        }
    }
    
    var attributedText: NSAttributedString? {
        didSet {
            initFrame()
        }
    }
    
    var inset: UIEdgeInsets = .zero {
        didSet {
            initFrame()
        }
    }
    
    var maxCount: Int = 0 {
        didSet {
            initFrame()
        }
    }
    
    var maxLine: Int = 0 {
        didSet {
            initFrame()
        }
    }
    
    override func _initUI() {
        lbl = YYLabel()
        lbl.font = .font(13)
        lbl.numberOfLines = 0
        lbl.textColor = .subTitle
        addSubview(lbl)
        
        btn = UIButton(type: .custom)
        btn.setTitle("展开", for: .normal)
        btn.setTitle("收起", for: .normal)
        btn.setTitleColor(._blue, for: .normal)
        btn.titleLabel?.font = .font(13)
        btn.backgroundColor = .white.withAlphaComponent(0.2)
//        addSubview(btn)
    }
    
    override func initFrame() {
        super.initFrame()
        
        if text == nil && attributedText == nil { return }
        if bounds.width == 0 { return }
        
        lbl.left(inset.left).right(bounds.width-inset.right).top(inset.top)
        var t = NSMutableAttributedString(string: "")
        t.yy_minimumLineHeight = 20.adapter
        t.yy_lineBreakMode = .byClipping
        if maxLine > 0 {
            if let str = text {
                t = str.text(font: font, color: textColor)
            }else if let at = attributedText {
                t = NSMutableAttributedString(attributedString: at)
            }
//            lbl.height(CGFloat(maxLine) * 20.adapter)
        }else if maxCount > 0 {
            if let str = text {
                t = str.sub(from: 0, to: maxCount).text(font: font, color: textColor)
            }else if let at = attributedText {
                t = NSMutableAttributedString(attributedString: at.attributedSubstring(from: NSMakeRange(0, maxCount)))
            }
        }
        lbl.attributedText = t
        let h = lbl.attributedText!.size(maxSize: CGSize(width: lbl.frame.width, height:.greatestFiniteMagnitude)).height
        lbl.height(ceil(h))
        btn.bottom(lbl.frame.maxY).right(lbl.frame.maxX).width(30.adapter).height(20.adapter)
        autoBottomInset = inset.bottom
        lastV = lbl
        autoHeight()
    }
    
    private var lbl: YYLabel!
    private var btn: UIButton!
}
